package com.uaf.aes.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uaf.aes.annotation.AesSecurity;
import com.uaf.aes.utils.AESUtilsDemo;
import com.uaf.aes.utils.FileStreamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author cailu
 * @filename EncodeResponseAdvice
 * @description 返回数据加密
 * @date 2020/5/6 14:42
 */
@ControllerAdvice(basePackages = "com.uaf.aes.contoller")
public class EncodeResponseAdvice implements ResponseBodyAdvice {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private static String PATH = "D:\\uaren\\aeskey\\aes.txt";

	@Override
	public boolean supports(MethodParameter methodParameter, Class aClass) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
	                              ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		boolean encode = false;
		if (methodParameter.getMethod().isAnnotationPresent(AesSecurity.class)) {
			//获取注解配置的包含和去除字段
			AesSecurity serializedField = methodParameter.getMethodAnnotation(AesSecurity.class);
			//出参是否需要加密
			encode = serializedField.outEncode();
		}
		if (encode) {
			logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回参数数据进行加密");
			ObjectMapper objectMapper = new ObjectMapper();
			try {
				String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
				String codeKey = FileStreamUtils.readToString(PATH);
				return AESUtilsDemo.encrypt(result, codeKey);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】数据进行解密出现异常：" + e.getMessage());
			}
		}
		return body;

	}
}
